using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Xml;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.Title = ConfigurationManager.AppSettings["LoginPageTitle"];

            WikiTools.Access.Wiki wiki = new WikiTools.Access.Wiki(ConfigurationManager.AppSettings["mWikiRootPath"], ConfigurationManager.AppSettings["mWikiCachePath"], ConfigurationManager.AppSettings["mWikiUsername"], ConfigurationManager.AppSettings["mWikiPassword"]);
//            wiki.Login(ConfigurationManager.AppSettings["mWikiUsername"], ConfigurationManager.AppSettings["mWikiPassword"]);


            //create if it does not exist
            wiki.CreatePage(ConfigurationManager.AppSettings["mWikiRootSurveyPage"], "new page", true);


            WikiTools.Access.Page page = new WikiTools.Access.Page(wiki, ConfigurationManager.AppSettings["mWikiRootSurveyPage"]);

            // set up the root page with all possible surveys
            StringBuilder wikiText = new StringBuilder();
            XmlDocument surveys = new XmlDocument();
            surveys.Load(ConfigurationManager.AppSettings["SurveysLocation"]);
            XmlNodeList surveyList = surveys.SelectNodes("Surveys/Survey");
            foreach (XmlNode survey in surveyList)
            {

                wikiText.AppendLine("[[" + ConfigurationManager.AppSettings["mWikiRootSurveyPage"] + " - " + survey.InnerXml + "]]");
                wikiText.AppendLine("");
            }

            page.SetText(wikiText.ToString());
        }

        SetFocus(SurveyLogin.FindControl("UserName"));
    }


    protected void SurveyLogin_Authenticate(object sender, AuthenticateEventArgs e)
    {
        XmlDocument users = new XmlDocument();
        users.Load(ConfigurationManager.AppSettings["UsersLocation"]);
        XmlNodeList usersList = users.SelectNodes("Users/User");
        foreach (XmlNode user in usersList)
        {

            if (user.Attributes["username"].Value == SurveyLogin.UserName && user.Attributes["password"].Value == SurveyLogin.Password)
            {
                e.Authenticated = true;
                break;

            }
        }

    }
}
